"""
测试完整的SOAP XML报文处理，包含Envelope、Header和Body中都有xmlns内容
"""

import tempfile
import os
from com.tools.Xml_Utils.xml_utils import XmlUtils


def test_complete_soap_xml():
    """
    测试完整的SOAP XML报文处理
    """
    print("测试完整的SOAP XML报文处理:")
    
    # 创建临时目录用于测试
    with tempfile.TemporaryDirectory() as temp_dir:
        # 完整的SOAP XML报文，包含Envelope、Header和Body中都有xmlns内容
        complete_soap_xml = """<?xml version="1.0" encoding="UTF-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
                       xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
            <soap:Header xmlns:head="http://example.com/headers">
                <wsa:Action>http://example.com/GetWeather</wsa:Action>
                <wsa:MessageID>uuid:12345678-1234-1234-1234-123456789012</wsa:MessageID>
                <head:Authentication>
                    <head:Username>testuser</head:Username>
                    <head:Password>testpass</head:Password>
                </head:Authentication>
            </soap:Header>
            <soap:Body xmlns:body="http://example.com/body">
                <body:GetWeatherRequest>
                    <body:CityName>Beijing</body:CityName>
                    <body:CountryName>China</body:CountryName>
                    <body:Units>Celsius</body:Units>
                </body:GetWeatherRequest>
            </soap:Body>
        </soap:Envelope>
        """
        
        print("原始SOAP XML:")
        print(complete_soap_xml)
        
        # 加载SOAP XML
        xml_obj = XmlUtils(xml_string=complete_soap_xml)
        
        # 测试命名空间解析
        print("\n测试命名空间解析:")
        namespaces = xml_obj.get_namespaces()
        print(f"解析到的命名空间: {namespaces}")
        
        # 验证关键命名空间是否存在
        assert "soap" in namespaces
        assert "wsa" in namespaces
        assert "head" in namespaces
        assert "body" in namespaces
        
        # 测试元素查找
        print("\n测试元素查找:")
        
        # 查找Header元素
        header = xml_obj.find_element(".//{http://schemas.xmlsoap.org/soap/envelope/}Header")
        print(f"Header元素存在: {header is not None}")
        assert header is not None
        
        # 查找Body元素
        body = xml_obj.find_element(".//{http://schemas.xmlsoap.org/soap/envelope/}Body")
        print(f"Body元素存在: {body is not None}")
        assert body is not None
        
        # 查找Action元素
        action = xml_obj.get_element_text(".//{http://schemas.xmlsoap.org/ws/2004/08/addressing}Action")
        print(f"Action内容: {action}")
        assert action == "http://example.com/GetWeather"
        
        # 查找MessageID元素
        message_id = xml_obj.get_element_text(".//{http://schemas.xmlsoap.org/ws/2004/08/addressing}MessageID")
        print(f"MessageID内容: {message_id}")
        assert "uuid:" in message_id
        
        # 查找认证信息
        username = xml_obj.get_element_text(".//{http://example.com/headers}Username")
        password = xml_obj.get_element_text(".//{http://example.com/headers}Password")
        print(f"用户名: {username}")
        print(f"密码: {password}")
        assert username == "testuser"
        assert password == "testpass"
        
        # 查找请求参数
        city = xml_obj.get_element_text(".//{http://example.com/body}CityName")
        country = xml_obj.get_element_text(".//{http://example.com/body}CountryName")
        units = xml_obj.get_element_text(".//{http://example.com/body}Units")
        print(f"城市: {city}")
        print(f"国家: {country}")
        print(f"单位: {units}")
        assert city == "Beijing"
        assert country == "China"
        assert units == "Celsius"
        
        # 测试元素修改
        print("\n测试元素修改:")
        
        # 修改城市名称
        xml_obj.set_element_text(".//{http://example.com/body}CityName", "Shanghai")
        
        # 修改认证信息
        xml_obj.set_element_text(".//{http://example.com/headers}Username", "newuser")
        xml_obj.set_element_text(".//{http://example.com/headers}Password", "newpass")
        
        # 验证修改结果
        new_city = xml_obj.get_element_text(".//{http://example.com/body}CityName")
        new_username = xml_obj.get_element_text(".//{http://example.com/headers}Username")
        new_password = xml_obj.get_element_text(".//{http://example.com/headers}Password")
        print(f"新城市: {new_city}")
        print(f"新用户名: {new_username}")
        print(f"新密码: {new_password}")
        assert new_city == "Shanghai"
        assert new_username == "newuser"
        assert new_password == "newpass"
        
        # 测试添加新元素
        print("\n测试添加新元素:")
        
        # 在Header中添加新元素
        header_element = xml_obj.find_element(".//{http://schemas.xmlsoap.org/soap/envelope/}Header")
        new_header_child = ET.SubElement(header_element, "{http://example.com/headers}SessionID")
        new_header_child.text = "SESSION12345"
        
        # 在Body中添加新元素
        body_element = xml_obj.find_element(".//{http://schemas.xmlsoap.org/soap/envelope/}Body")
        new_body_child = ET.SubElement(body_element, "{http://example.com/body}RequestTime")
        new_body_child.text = "2023-01-01T12:00:00Z"
        
        # 验证新元素
        session_id = xml_obj.get_element_text(".//{http://example.com/headers}SessionID")
        request_time = xml_obj.get_element_text(".//{http://example.com/body}RequestTime")
        print(f"会话ID: {session_id}")
        print(f"请求时间: {request_time}")
        assert session_id == "SESSION12345"
        assert request_time == "2023-01-01T12:00:00Z"
        
        # 测试属性操作
        print("\n测试属性操作:")
        
        # 为Body元素添加属性
        body_element.set("body:id", "BODY001")
        
        # 获取Body元素的属性
        body_id = xml_obj.get_element_attribute(".//{http://schemas.xmlsoap.org/soap/envelope/}Body", "body:id")
        print(f"Body ID属性: {body_id}")
        assert body_id == "BODY001"
        
        # 测试保存和加载
        print("\n测试保存和加载:")
        soap_file = os.path.join(temp_dir, "complete_soap_test.xml")
        xml_obj.save_to_file(soap_file)
        print(f"SOAP XML已保存到: {soap_file}")
        
        # 从文件加载
        xml_obj2 = XmlUtils(xml_path=soap_file)
        loaded_city = xml_obj2.get_element_text(".//{http://example.com/body}CityName")
        loaded_username = xml_obj2.get_element_text(".//{http://example.com/headers}Username")
        print(f"加载的城市: {loaded_city}")
        print(f"加载的用户名: {loaded_username}")
        assert loaded_city == "Shanghai"
        assert loaded_username == "newuser"
        
        # 测试转换为字符串
        print("\n测试转换为字符串:")
        xml_string = xml_obj.to_string()
        print("XML字符串长度:", len(xml_string))
        
        # 验证关键信息在字符串中
        assert "Shanghai" in xml_string
        assert "newuser" in xml_string
        assert "SESSION12345" in xml_string
        assert "2023-01-01T12:00:00Z" in xml_string
        
        print("\n所有完整SOAP XML测试通过!")


def test_soap_with_response():
    """
    测试包含响应的SOAP XML处理
    """
    print("\n\n测试包含响应的SOAP XML处理:")
    
    # 包含响应的SOAP XML
    soap_with_response = """<?xml version="1.0" encoding="UTF-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
                   xmlns:web="http://www.webserviceX.NET">
        <soap:Header/>
        <soap:Body xmlns:resp="http://example.com/response">
            <web:GetWeather>
                <web:CityName>Beijing</web:CityName>
                <web:CountryName>China</web:CountryName>
            </web:GetWeather>
            <resp:GetWeatherResponse>
                <resp:WeatherData>
                    <resp:Location>Beijing</resp:Location>
                    <resp:Temperature>10</resp:Temperature>
                    <resp:Humidity>65</resp:Humidity>
                    <resp:Condition>Sunny</resp:Condition>
                </resp:WeatherData>
                <resp:Status>Success</resp:Status>
            </resp:GetWeatherResponse>
        </soap:Body>
    </soap:Envelope>
    """
    
    xml_obj = XmlUtils(xml_string=soap_with_response)
    
    # 测试请求数据提取
    print("测试请求数据提取:")
    request_city = xml_obj.get_element_text(".//{http://www.webserviceX.NET}CityName")
    request_country = xml_obj.get_element_text(".//{http://www.webserviceX.NET}CountryName")
    print(f"请求城市: {request_city}")
    print(f"请求国家: {request_country}")
    assert request_city == "Beijing"
    assert request_country == "China"
    
    # 测试响应数据提取
    print("\n测试响应数据提取:")
    location = xml_obj.get_element_text(".//{http://example.com/response}Location")
    temperature = xml_obj.get_element_text(".//{http://example.com/response}Temperature")
    humidity = xml_obj.get_element_text(".//{http://example.com/response}Humidity")
    condition = xml_obj.get_element_text(".//{http://example.com/response}Condition")
    status = xml_obj.get_element_text(".//{http://example.com/response}Status")
    print(f"位置: {location}")
    print(f"温度: {temperature}")
    print(f"湿度: {humidity}")
    print(f"天气状况: {condition}")
    print(f"状态: {status}")
    assert location == "Beijing"
    assert temperature == "10"
    assert humidity == "65"
    assert condition == "Sunny"
    assert status == "Success"
    
    # 测试数值转换
    temp_value = int(temperature)
    humidity_value = int(humidity)
    print(f"温度数值: {temp_value}°C")
    print(f"湿度数值: {humidity_value}%")
    assert temp_value == 10
    assert humidity_value == 65
    
    print("SOAP响应处理测试通过!")


# 由于我们在方法内部使用了ET，需要导入
import xml.etree.ElementTree as ET


if __name__ == "__main__":
    test_complete_soap_xml()
    test_soap_with_response()